/**
 * @description webpack 公共的配置文件
 * @author fyj
 */

const path = require('path');
const webpack = require('webpack');
const { VueLoaderPlugin } = require('vue-loader');
const { merge } = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMiniPlugin = require('css-minimizer-webpack-plugin');
const devConfig = require('./webpack.dev');
const prodConfig = require('./webpack.prod');

const commonConfig = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/[name].bundle.js'
  },
  resolve: {
    extensions: ['.js', '.json', '.wasm', '.vue'],
  },
  optimization: {
    usedExports: true,
    runtimeChunk: true,
    minimize: true,
    minimizer: [
      new TerserPlugin({
        extractComments: false,
        minify: TerserPlugin.uglifyJsMinify,
      }),
      new CssMiniPlugin(),
    ],
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        defaultVendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
          filename: 'js/[name].vendor.js',
        },
        default: {
          minChunks: 2,
          priority: -20,
          filename: 'js/[name].chunk.js',
        },
      },
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        use: 'vue-loader'
      },
      {
        test: /\.js$/,
        use: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.less$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader']
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader']
      },
      {
        test: /\.(png|jpe?g)$/,
        type: 'asset/inline'
      }
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
    new webpack.DefinePlugin({
      BASE_URL: JSON.stringify('./')
    }),
    new HtmlWebpackPlugin({
      title: 'vue 开发中 webpack 的配置',
      template: './public/index.html'
    }),
    new MiniCssExtractPlugin({
      filename: 'css/[name].css'
    }),
  ]
}

module.exports = (args) => {
  const isProduction = args.production ? true : false;
  // process.env.NODE_ENV = isProduction ? 'production' : 'development';
  const config = isProduction ? prodConfig : devConfig;
  return merge(commonConfig, config);
}
